<!--
 * @Description: 添加字典项-明细-弹窗
 * @FilePath: \hk-iot\src\views\system\dic\component\addDicTypeDetailsDialog.vue
 * @Date: 2023-07-27 09:43:13
 * @LastEditTime: 2023-11-30 09:01:09
-->
<template>
  <div class="box-container energy-from energy-dialog">
    <el-dialog center align-center v-model="state.isShowDialog" width="40%">
      <template #header="{ titleClass }">
        <div :class="titleClass">{{ state.isAdd ? '新增' : '修改' }}</div>
      </template>

      <el-form ref="sendSingleFormRef" :rules="state.rules" :model="state.ruleForm" size="default" label-width="100px">
        <el-row :gutter="30">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="上级节点" prop="parentId">
              <el-cascader :options="state.cascaderOptions" :props="cascaderProps" v-model="state.ruleForm.parentId"
                clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="字典名称" prop="name">
              <el-input @input="onVerifyAndSpace1($event)" v-model="state.ruleForm.name" placeholder="请输入名称"
                clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="字典键值" prop="code">
              <el-input @input="onVerifyAndSpace2($event)" v-model="state.ruleForm.code" placeholder="请输入键值"
                clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="字典排序" prop="seq">
              <el-input-number v-model="state.ruleForm.seq" :min="1" :max="100" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="字典备注" prop="remark">
              <el-input v-model="state.ruleForm.remark" placeholder="请输入备注" clearable type="textarea"> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="flex row-center mt10 mb10">
        <div class="btn3" @click="onCancel">
          <el-icon> <ele-Close /> </el-icon><span class="ml6">取 消</span>
        </div>
        <div class="btn1  ml10" @click="onSubmit(sendSingleFormRef)">
          <el-icon> <ele-Check /> </el-icon><span class="ml6">保 存</span>
        </div>

      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="addDicTypeDetailsDialog">
import { reactive, ref } from 'vue';
import { useDicApi } from '/@/api/system/dic';
import { ElMessage, FormInstance } from 'element-plus';
import {
  verifyAndSpace, //消除空格的
} from '/@/utils/toolsValidate'; // 工具类

const sendSingleFormRef = ref<FormInstance>();

const state = reactive<any>({
  isShowDialog: false,
  isAdd: true,
  ruleForm: {
    typeId: '', // 左侧大项的id
    parentId: '', // 上级节点id
    id: '', // 当前子项的id(修改时需要，新增不需要)
    name: '', // 当前子项的name
    code: '',
    seq: 1, // 排序
    remark: '', // 备注
  },
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入键值', trigger: 'blur' }],
  },

  cascaderOptions: [],
});

const cascaderProps = {
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'list',
};

const emit = defineEmits(['onParamSubmit']); // 子传父

// 禁止输入空格
const onVerifyAndSpace1 = (val: string) => {
  state.ruleForm.name = verifyAndSpace(val);
};
const onVerifyAndSpace2 = (val: string) => {
  state.ruleForm.code = verifyAndSpace(val);
};

// 打开弹窗
const openDialog = async (left: any, right: any, row: any = null) => {
  state.ruleForm.typeId = left.id;
  if (!row) {
    // 新增
    state.isAdd = true;
    state.cascaderOptions = right;
    state.ruleForm.parentId = ''; // 上级节点id
    Reflect.deleteProperty(state.ruleForm, 'id');
    state.ruleForm.name = '';
    state.ruleForm.code = '';
    state.ruleForm.seq = 1;
    state.ruleForm.remark = '';
  } else {
    // 编辑
    state.isAdd = false;
    state.cascaderOptions = addTreeDisabled(right, row.id);
    state.ruleForm.typeId = row.typeId; // 左侧大项的id
    state.ruleForm.parentId = row.parentId; // 上级节点id
    state.ruleForm.id = row.id; // 当前子项的id(修改时需要，新增不需要)
    state.ruleForm.name = row.name; // 当前子项的name
    state.ruleForm.code = row.code; // 当前值
    state.ruleForm.seq = row.seq; // 排序
    state.ruleForm.remark = row.remark; // 备注
  }
  state.isShowDialog = true;
};

// 行内新增
const openDialogOnRow = (left: any, right: any, row: any = null) => {
  state.isAdd = true;
  state.isShowDialog = true;
  state.ruleForm.typeId = left.id;
  state.ruleForm.parentId = row.id; // 上级节点id
  state.cascaderOptions = right;
  Reflect.deleteProperty(state.ruleForm, 'id');
  state.ruleForm.name = '';
  state.ruleForm.seq = 1;
  state.ruleForm.remark = '';
};

// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 添加树状结构的禁用项
const addTreeDisabled = (tree: any[], curId: string) => {
  tree.forEach((item: any) => {
    item.disabled = item.id == curId ? true : false;
    if (item.children) {
      addTreeDisabled(item.children, curId);
    }
  });
  return tree;
};

// 表单提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      let length = state.ruleForm.parentId?.length;
      if (length && Object.prototype.toString.call(state.ruleForm.parentId) == '[object Array]') {
        state.ruleForm.parentId = state.ruleForm.parentId[length - 1];
      }

      if (state.isAdd) {
        await useDicApi()
          .createDictionaryDetail(state.ruleForm)
          .then((data: any) => {
            emit('onParamSubmit', data);
            ElMessage.success(data.msg || '新增成功');
            closeDialog();
          });
      } else {
        // 如果是编辑
        await useDicApi()
          .updateDictionaryDetail(state.ruleForm)
          .then((data: any) => {
            emit('onParamSubmit', data);
            ElMessage.success(data.msg || '更新成功');
            closeDialog();
          });
      }
    } else {
      ElMessage.warning('表格项验证失败,请检查');
      console.log('表格项验证失败!', fields);
    }
  });
};

//弹出方法
defineExpose({
  openDialog,
  openDialogOnRow,
  closeDialog,
  onCancel,
  onSubmit,
});
</script>

<style scoped lang="scss">
.mb20 {
  z-index: 0;
}

.mb20-cascadeValue {
  z-index: 1;
}

:deep(.el-form-item__label) {
  width: 91px;
}</style>
